import { defineStore } from 'pinia';
import { useUserStore } from './user-info';
import { showToast } from 'vant';
import { checkToken } from '@/api/login';
import { useRouter } from 'vue-router';

interface Account {
  id: number;
  name: string;
  email: string;
  accessToken: string; // 可选属性
  refreshToken: string; // 可选属性
}

export const useMultiAccountStore = defineStore('multi-account', {
  state: () => ({
    accounts: [] as Account[],
    currentAccountId: null as number | null,
  }),

  getters: {
    currentAccount(state): Account | undefined {
      return state.accounts.find((acc) => acc.id === state.currentAccountId);
    },
  },

  actions: {
    init() {
      const savedId = localStorage.getItem('currentAccountId');
      const found = this.accounts.find((a) => String(a.id) === savedId);
      if (found) {
        this.currentAccountId = found.id;
      }
    },

    // ✅ 激活选中的账号
    async activateAccount(accountId: number) {
      const router = useRouter(); // 获取路由实例

      const account = this.accounts.find((acc) => acc.id === accountId);
      if (!account) return;

      const userStore = useUserStore();
      const previousAccountId = this.currentAccountId;

      try {
        // 👇 校验 token 有效性
        const res = await checkToken(account.accessToken);

        if (res.code === 0 && typeof res.data.exp === 'number') {
          // ✅ token 有效，继续激活账号
          this.currentAccountId = account.id;
          localStorage.setItem('currentAccountId', String(account.id));

          userStore.accessToken = account.accessToken;
          userStore.refreshToken = account.refreshToken;

          await userStore.getUserInfoAction();
          showToast(`已切换到 ${account.name}`);
        } else {
          throw new Error('Token invalid');
        }
      } catch (err: any) {
        console.warn('⚠️ Token 无效，移除账号', err);
        this.removeAccount(account.id);
        showToast('该账号已过期，已自动清除');

        // 🔴 如果已经没有账号了，跳转登录
        if (this.accounts.length === 0) {
          router.replace({ name: 'login' }); // 或者 path: '/login'
        }

        // 如果之前有账号，自动切回
        if (previousAccountId && previousAccountId !== accountId) {
          await this.activateAccount(previousAccountId);
        }
      }
    },

    /**
     * 将 userStore 中的信息同步进账户列表
     */
    async addOrUpdateAccountFromUserInfo(userStore: ReturnType<typeof useUserStore>) {
      const account: Account = {
        id: userStore.userInfo.userId,
        name: userStore.userInfo.fullName,
        email: userStore.userInfo.email,
        accessToken: userStore.accessToken,
        refreshToken: userStore.refreshToken,
      };

      const existing = this.accounts.find((acc: { id: number }) => acc.id === account.id);

      if (existing) {
        Object.assign(existing, account);
      } else {
        this.accounts.push(account);
      }

      this.currentAccountId = account.id;
      localStorage.setItem('currentAccountId', String(account.id));
    },

    removeAccount(accountId: number) {
      const wasCurrent = this.currentAccountId === accountId;

      // 1. 过滤掉目标账号
      this.accounts = this.accounts.filter((acc: { id: number }) => acc.id !== accountId);

      // 2. 如果删除的是当前账号，清空状态
      if (wasCurrent) {
        this.currentAccountId = null;
        localStorage.removeItem('currentAccountId');

        const userStore = useUserStore();
        userStore.clearLock(); // 清空 accessToken、refreshToken、userInfo 等
      }
    },
  },

  persist: true,
});
